-- 界面部分
-- ui跟随鼠标移动，cv的
local function FollowMouseForUI(UI, func_stop)
    UI.FollowMouse = function(self)
        if self.followhandler == nil then
            local cur_pos = TheInput:GetScreenPosition()
            local scale = 1 / UI.parent:GetLooseScale()
            local ori_pos = self:GetPosition()
            self.followhandler = TheInput:AddMoveHandler(function(x, y)
                self:SetPosition((Vector3(x, y, 0) - cur_pos) * scale + ori_pos)
            end)
        end
    end
    local _OnMouseButton = UI.OnMouseButton
    UI.OnMouseButton = function(ui, press, down, ...)
        local result = _OnMouseButton(ui, press, down, ...)
        if press == MOUSEBUTTON_RIGHT then
            if down then
                return ui:FollowMouse()
            elseif type(func_stop) == "function" then
                func_stop(ui:GetPosition())
            end
        end
        ui:StopFollowMouse()
        return result
    end
end

local TaFragmentateBadge = require("widgets/ta_fragmentate_badge")
local function AddTaFragmentateBadge(self)
    if self.owner.prefab ~= "twilight_archangel" then
        return
    end
    self.ta_fragmentate_badge = self:AddChild(TaFragmentateBadge(self.owner))

    FollowMouseForUI(self.ta_fragmentate_badge, function(pos)
        self.ta_fragmentate_badge:SetPosition(pos)
    end)

    -- 延迟一点 然后放到 饥饿的左边
    self.owner:DoTaskInTime(0.5, function()
        local x1, y1, z1 = self.stomach:GetPosition():Get()
        local x2, y2, z2 = self.brain:GetPosition():Get()
        local x3, y3, z3 = self.heart:GetPosition():Get()
        if y2 == y1 or y2 == y3 then -- 开了三维mod
            self.ta_fragmentate_badge:SetPosition(self.stomach:GetPosition() + Vector3((x1 - x2) * 1.5, 0, 0))
        else
            self.ta_fragmentate_badge:SetPosition(self.stomach:GetPosition() + Vector3((x1 - x3) * 1.5, 0, 0))
        end
    end)

    -- 监听事件 刷新数据
    self.inst:ListenForEvent("ta_fragmentate_delta", function(inst, data)
        self.ta_fragmentate_badge:SetPercent(data, self.owner.replica.ta_fragmentate:Max())
    end, self.owner)

    -- 死亡时候的隐藏
    local old_SetGhostMode = self.SetGhostMode
    function self:SetGhostMode(ghostmode, ...)
        old_SetGhostMode(self, ghostmode, ...)
        if ghostmode then
            if self.ta_fragmentate_badge ~= nil then
                self.ta_fragmentate_badge:Hide()
            end
        else
            if self.ta_fragmentate_badge ~= nil then
                self.ta_fragmentate_badge:Show()
            end
        end
    end

end
AddClassPostConstruct("widgets/statusdisplays", AddTaFragmentateBadge)
